<template>
  <view class="bg-white image-container-box">
    <view v-if="show" class="padding-top-30 padding-lr-40 flex-row justify-between flex-wrap image-conten-page" style="display: block !important;">
      <view v-for="(val,key) in list" :key="key" class="flex-column flex-center margin-bottom-30 image-conten-list" style="width: 100%;justify-content: flex-start !important;">
		<block v-if="imageFlag(val).split(',').length > 0 && imageFlag(val).split(',')[0] != ''">
			<block v-for="(item,index) in imageFlag(val).split(',')" :key="item">
				<view style="margin-bottom: 10rpx;width: 49%;">
					<view class="img" style="margin: 0 auto;"  @longpress="deleteImg(val.attr,item)"  @click="uploadImg(val.attr,val,key,item,index)">
					  <image class="img block" :src="item" mode="aspectFill" />
					</view>
					<view class="flex-row flex-center margin-top-30">
					  <text v-if="must || val.must" class="text-30 color-error margin-right-6">*</text>
					  <text class="text-26 color-t3">{{ val.label }}</text>
					  <text v-if="val.example && !disabled" class="text-26 color-primary margin-left-14" @click="showExampleImage(item)">示例图</text>
					</view>
				</view>
			</block>
		</block>
		<block v-else>
			<view class="img" @click="uploadImg(val.attr,key)">
			  <image class="img block" :src="imageFlag(val)" mode="aspectFill" />
			</view>
			<view class="flex-row flex-center margin-top-30">
			  <text v-if="must || val.must" class="text-30 color-error margin-right-6">*</text>
			  <text class="text-26 color-t3">{{ val.label }}</text>
			  <text v-if="val.example && !disabled" class="text-26 color-primary margin-left-14" @click="showExampleImage(val)">示例图</text>
			</view>
		</block>
      </view>
    </view>

    <tui-modal :show.sync="showModal" :title="errMsg.title" :content="errMsg.msg" @click="modalClick" />
	<tui-modal
	    :show="showDelete"
	    mask-closable
	    title="删除图片"
		:button="[{ text: '确定', type: '',plain: false  }]"
	    content="确认删除该图片吗？"
	    @click="deleteSure"
	    @cancel="show = false"
	/>
  </view>
</template>

<script>
import { saveImage, openSetting, viewImage, loading } from '@/common/util'
import { recognizeIdCard, recognizeIdCardBack, recognizeDriverLicense, recognizeDrivingLicense, recognizeBusinessLicense } from '@/common/api/ai.js'
export default {
  name: 'ImageModel',
  props: {
	auditCv: {
		type:Boolean,
		default:false
	},
    must: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    },
    defaultImg: {
      type: String,
      default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-admin-uniapp/card_cert.png'
    },
    show: {
      type: Boolean,
      default: true
    },
    list: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        idCard1: '',
        idCard2: '',
        licence1: '',
        certification: '',
        compulsoryInsPic: '',
        carrierInsPic: '',
        commerceInsPic: '',
        vlicencePicture: '',
        bizPicture: '',
        idCard: '',
        idCardBackground: '',
        licence: '',
        transportLicence: '',
        bank: '',
        safeLicence: ''
      },
      showModal: false,
	    showDelete: false,
		key:'',
		path:'',
      errMsg: {
        title: '',
        msg: ''
      }
    }
  },
  computed: {
    imgList() {
      const arr = []
      this.list.forEach(item => {

        if (this.form[item.attr]) arr.push(this.form[item.attr])
      })
      return arr
    }
  },
  watch: {
    data: {
      handler(e) {
        Object.keys(this.form).forEach(item => {
          this.form[item] = e[item]
        })
      },
      deep: true
    },
    form: {
      handler(newVal) {
        this.$emit('update',newVal)
      },
      deep: true
    }
  },
  created() {
    this.form = this.copyData(this.data)
	console.log(this.form,'form')
  },
  methods: {
	  imageFlag(data){
		  if(this.form[data.attr] && this.form[data.attr] != '暂无'){
			  if(this.form[data.attr].split(',').length == 6 || this.auditCv)  {
				  return this.form[data.attr]}
				else{
				  return this.form[data.attr]+','+ data.default
				}
			
		  }else if(data.default){
			  return data.default
		  }else{
			  return this.defaultImg
		  } 
	  },
	  //删除照片
	  deleteImg(key,path){
		  console.log('我来了');
		   console.log(!this.auditCv);
		   if(this.auditCv) return
		  
		  let  arr = this.form[key].split(',')
		  if(!arr.includes(path) )  return 
		
		this.showDelete = true
		this.key = key
		this.path = path
	  },
	  deleteSure(){
		  let arr = this.form[this.key].split(',')
		  arr.forEach((item,key) =>{
		  		if(item == this.path ){
		  			arr.splice(key,1)
		  			} 
		  })
		  
		   this.form[this.key ] = arr.join(',')
		   this.showDelete = false
		   this.key = ''
		   this.path = ''
	  },
    // 上传图片
    uploadImg(attr, current,key,item,index) {
		console.log("this.disabled："+this.disabled);
		console.log("this.auditCv："+this.auditCv, this.imgList);
      if (this.disabled) {
        if (this.imgList) viewImage(index,this.form[attr].split(','))
      } else {
		  if(this.auditCv){
			  if(attr == 'vlicencePicture' || attr == 'bizPicture' || attr == 'compulsoryInsPic' || attr == 'carrierInsPic'){
				  return false
			  }
		  }
        saveImage(this.dir).then(imgUrl => {
			// 判断是否进行数据修改
			if(this.auditCv){
				let cv = this.form[attr].split(",")
				cv[index] = imgUrl
				this.form[attr] = cv.join(',')
			}else{
				// 添加图片
				let arr = ['tbb_admin_app/static/baoxian.png','tbb-portal/static/singshizheng.png','tbb-portal/static/zigezheng.png']
				let judge = false
				for(let i= 0 ;i<=arr.length - 1;i++){
					console.log(item)
					console.log(item.indexOf(arr[i]))
					if(item.indexOf(arr[i]) >= 0){
						judge = true
					}
				}
				let cv = this.form[attr].split(",")
				cv[index] = imgUrl
				this.form[attr] = cv.join(',')
				// if(!judge){
				// 	let cv = this.form[attr].split(",")
				// 	cv[index] = imgUrl
				// 	this.form[attr] = cv.join(',')
				// }else{
				// 	if(this.form[attr].split(",").length <= 6){
				// 		// if(this.form[attr] == ''){
				// 		// 	this.form[attr] += this.list[key].default
				// 		// }
				// 		this.form[attr] = this.form[attr].split(",")
				// 		let attCv = this.form[attr][this.form[attr].length - 1]
				// 		this.form[attr].splice(this.form[attr].length - 1,1)
				// 		this.form[attr].push(imgUrl)
				// 		this.form[attr].push(attCv)
				// 		if(this.form[attr].length > 6){
				// 			this.form[attr].splice(this.form[attr].length - 1,1)
				// 		}
				// 		this.form[attr] = this.form[attr].join(',')
				// 	}
				// }
			}
	
          this.recognition(attr, imgUrl)
        }).catch(err => {
          this.showModal = true
          this.errMsg = err
        })
      }
    },
    // 智能识别中
    async recognition(attr, imgUrl) {
      let err
      let res
      const l = loading('智能识别中')
      if (attr === 'idCard1' || attr === 'idCard') [err, res] = await recognizeIdCard({ imgUrl })
      else if (attr === 'idCard2' || attr === 'idCardBackground') [err, res] = await recognizeIdCardBack({ imgUrl })
      else if (attr === 'licence1') [err, res] = await recognizeDriverLicense({ imgUrl })
      else if (attr === 'vlicencePicture') [err, res] = await recognizeDrivingLicense({ imgUrl })
      else if (attr === 'licence') [err, res] = await recognizeBusinessLicense({ imgUrl })
      else {
        l.hide()
        return
      }
      l.hide()
      if (this.$http.errorCheck(err, res)) {
        this.toast('识别成功')
        const data = res.data.data
        if (attr === 'idCard1') {
          this.form.nickname = data.name
          this.form.idCardNo = data.id
          this.form.address = data.address
          if (data.gender == '女') this.form.gender = 1
          else if (data.gender == '男') this.form.gender = 0
        } else if (attr === 'idCard2') {
          this.form.idCardValidDate = data.startDate
          this.form.idCardValidDateEnd = data.endDate == -1 ? '长期' : data.endDate
        } else if (attr === 'licence1') {
          this.form.licenceNo = data.id
          this.form.validStartDate = this.formatDate(data.startDate)
          this.form.issueDate = this.formatDate(data.issueDate)
          this.form.validEndDate = this.formatDate(data.endDate)
          this.form.licenceType = data.vehicleType
        } else if (attr === 'vlicencePicture') {
          this.form.vlicenceRegister = this.formatDate(data.registerDate)
          this.form.frameNumber = data.vin
          this.form.engineNumber = data.engineNumber
          this.form.brandModel = data.model
          this.form.useType = data.useCharacter
          if (this.form.number && this.form.number != data.plateNumber) {
            this.toast('车牌号已更新为' + data.plateNumber)
          }
          this.form.number = data.plateNumber
        } else if (attr === 'licence') {
          this.form.company = data.name
          this.form.socialUnifiedCode = data.registerNumber
        } else if (attr === 'idCard') {
          this.form.idCardName = data.name
          this.form.idCardValue = data.id
        } else if (attr === 'idCardBackground') {
          this.form.idCardValidDate = data.startDate
          this.form.idCardValidDateEnd = data.endDate < 0 ? '长期' : data.endDate
        }
      }
    },
    // 格式化时间
    formatDate(date) {
      return date.substr(0, 4) + '-' + date.substr(4, 2) + '-' + date.substr(6, 2)
    },
    // 展示示例图
    showExampleImage(item) {
      this.$emit('showExampleImage', item)
    },
    // 打开设置
    modalClick(e) {
      this.showModal = false
      if (e.index && this.errMsg.code === 1025) {
        openSetting()
      }
    }
  }
}
</script>

<style scoped lang="scss">
@include setMargin(right,6);

@include setMargin(left,14);

.image-container-box{
  border-radius: 0 0 14rpx 14rpx;
  overflow: hidden;
  width: 100%;
}
.img{
  width:250rpx;
  height:168rpx;
}
.image-conten-page{
	width: 100% !important;
	overflow: hidden !important;
	justify-content: space-between !important;
	flex-wrap: wrap !important;
}
.image-conten-list{
	justify-content: flex-start !important;
	flex-direction: row !important;
	flex-wrap: wrap !important;
	justify-content: space-between !important;
	border-bottom: 2rpx solid #e1e1e1 !important;
	padding-bottom: 10rpx;margin-bottom: 20rpx !important;
}
</style>
